package cn.edu.zut.score.core.aop;

import cn.edu.zut.score.core.domain.RestResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author zby
 * @date 2021/06/25
 */
@Aspect
@Component
public class ControllerAop {

    private static final Logger logger = LoggerFactory.getLogger(ControllerAop.class);

    @Around("execution(public cn.edu.zut.score.core.domain.RestResponse *(..))")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        RestResponse<?> result;
        try {
            result = (RestResponse<?>) pjp.proceed();
            if (pjp.getSignature().getName().endsWith("login")) {
                logger.info("{}, time: {}", pjp.getSignature(), System.currentTimeMillis() - startTime);
            } else {
                logger.info("{} args: {}, time: {}", pjp.getSignature(), pjp.getArgs(), System.currentTimeMillis() - startTime);
            }
        } catch (Throwable e) {
            result = handleException(pjp, e);
        }
        return result;
    }

    private RestResponse<String> handleException(ProceedingJoinPoint pjp, Throwable e) {
        logger.error(pjp.getSignature() + " error ", e);
        e.printStackTrace();
        return RestResponse.fail(e.getMessage());
    }
}
